<?php

namespace App\Services;

use App\Http\Controllers\Controller;
use App\Models\GoodCate;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Cache;

class GoodCateService extends Controller
{
    //获取分类列表
    public function getCateList() {
        $cate = Cache::rememberForever('good_category', function () {
            return GoodCate::all()->toArray();
        });

        $cate = array_values(Arr::sort($cate, function ($value) {
            return $value['sort'];
        }));
        return $this->toJSON(0, '',count($cate),$cate);
    }
    //保存分类
    public function goodCateStore($request) {
        $para = $request->except('_token');
        $goodCates = new GoodCate($para);
        $result = $goodCates->save();
        if (!$result) {
            return $this->toJSON(1001, '操作失败，请稍后再试');
        }
        $cateList = GoodCate::all()->toArray();
        Cache::forever('good_category', $cateList);
        return $this->toJSON(200);
    }
    //更新分类
    public function goodCateUpdate($request) {
        $id = (int)$request->input('id');
        if ($id < 1) {
            return $this->toJSON(1001, '操作失败，请稍后再试');
        }
        $goodCate = GoodCate::find($id);
        $goodCate->name = $request->input('name');
        $goodCate->sort = $request->input('sort');
        $status = $goodCate->save();
        if (!$status) {
            return $this->toJSON(1001, '操作失败，请稍后再试');
        }
        $cateList = GoodCate::all()->toArray();
        Cache::forever('good_category', $cateList);
        return $this->toJSON(200);
    }
}
